<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use App\Models\Book;
use App\Models\BookUpload;

class BookSortJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public $chapter_table = "";
    public $book_id = "";
    public function __construct($chapterTable,$bookId)
    {
        //
        $this->chapter_table = $chapterTable;
        $this->book_id = $bookId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $chapter = DB::table($this->chapter_table)
            ->where('book_id',$this->book_id)
            ->select(['id'])
            ->get();
        $total = count($chapter);
        $book_sort = DB::table("book_sort")->where('book_id',$this->book_id)->first();
        $sort = empty($book_sort) ? 0 : $book_sort->sort;
        if($sort == 0){//该书籍没有 开启书籍章节 一键排序
            $start_num =0;
            $for_num = 100;
            DB::table("book_sort")->insert(['book_id' => $this->book_id]);
        }else{
            $start_num = $sort+1;
            $for_num = ($total-100) > 100 ? $start_num + 100 : $total ;
        }
        for($i = $start_num;$i < $for_num;$i++){
            if(empty($chapter[$i]->id) || !isset($chapter[$i]->id)) continue;
            DB::table($this->chapter_table)->where('id',$chapter[$i]->id)->update(['index' => $i]);
        }
        if($total-$for_num <= 0){
            //全部更新完成
            DB::table("book_sort")->where('book_id',$this->book_id)->delete();
        }else{
            DB::table("book_sort")->where('book_id',$this->book_id)->update(['sort' => $for_num]);
        }
    }
}
